package jp.ne.iforce.android.jschatest;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class ToastService extends Service {

	public static Handler mH;
	public MediaPlayer mMediaPlayer;
    public Toast toastText;
    public Vibrator vibrator;

    public CreateProductHelper helper;
    public SQLiteDatabase db;



	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate(){
		Log.d("ToastService","onCreate");

        mH = new Handler() {
            @Override
			public void handleMessage(android.os.Message msg) {
            	Log.d("handleMessage","onCreate");
                if (msg.getData().getBoolean("receivedMessageFlag")) {

                	String type = msg.getData().getString("receivedTypeString");
                	String message = msg.getData().getString("receivedMessageString");
                	String level = msg.getData().getString("receivedLevelString");
                	String sec = msg.getData().getString("receivedSecString");
                	String tsunami = msg.getData().getString("receivedTsunamiString");

                    //ToastにViewを設定して表示
                	toastText = new Toast(ToastService.this);
                    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
                    if(type.equals("message")){
                    	View v = inflater.inflate(R.layout.message, null);
                    	insertList("kuma",message);
                    	selectMessageAll();

                        TextView textView = (TextView) v.findViewById(R.id.messagetext);
                        textView.setText(message);

                        //端末通知音
                        mMediaPlayer = MediaPlayer.create(ToastService.this, Settings.System.DEFAULT_NOTIFICATION_URI);

                        toastText.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL, 0, 0);
                        toastText.setView(v);
                    }else if(type.equals("earthquake")){
                    	View v = inflater.inflate(R.layout.earthquake, null);

                    	TextView textView = (TextView) v.findViewById(R.id.earthtext);
                        textView.setText("地震が発生しました。強い揺れに警戒してください。\n予想震度：" + level + "   到達予想時間：" + sec +"   津波："+tsunami);

                        //地震警報音
                        mMediaPlayer = MediaPlayer.create(ToastService.this, R.raw.jishin);

                        toastText.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
                        toastText.setView(v);
                    }
                    mMediaPlayer.start();

                    //バイブレータ
                    vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                    vibrator.vibrate(300);

                    //Toast表示
                    toastText.setDuration(Toast.LENGTH_LONG);
                    toastText.show();
                }
            }
        };
	}

	@Override
	public void onStart(Intent intent, int StartId) {
	}

	@Override
	public void onDestroy() {
	}

    /**
     * メッセージ登録
     * @param fromuser
     * @param message
     * @return
     */
    public boolean insertList(String fromuser,String message){
    	helper = new CreateProductHelper(this);
    	db = helper.getWritableDatabase();

    	//テーブル存在確認
    	String query = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='t_message';";
    	Cursor c = db.rawQuery(query, null);
    	c.moveToFirst();
    	String result = c.getString(0);

    	//なければ生成
    	if(result.equals("0")){
    		try{
    			String createSQL = "CREATE TABLE t_message(_id integer primary key autoincrement,"+
    												"fromuser text,"+
    												"time timestamp DEFAULT CURRENT_TIMESTAMP,"+
    												"message text)";
    			db.execSQL(createSQL);
    		}catch (Exception e) {
				Log.d("insertList","ERROR!!CREATE FAILED");
				return false;
			}
    	}

    	//メッセージ登録
    	try{
    		db.beginTransaction();		//トランザクション開始

    		ContentValues val = new ContentValues();
    		val.put("fromuser",fromuser);
    		val.put("message",message);

    		db.insert("t_message",null, val);
    		db.setTransactionSuccessful();		//コミット
    		db.endTransaction();				//トランザクション終了
    		db.close();
    	}catch (Exception e) {
    		Log.d("insertList","ERROR!!INSERT FAILED");
    		return false;
		}

    	return true;
    }

    /**
     * メッセージ履歴全件取得
     * @return
     */
    public Cursor selectMessageAll(){
    	helper = new CreateProductHelper(this);
    	db = helper.getWritableDatabase();
    	Cursor cursol = null;
    	try{
    		String selectAll = "SELECT _id,datetime(time, '+9 hours'),fromuser,message FROM t_message ORDER BY time DESC";
    		cursol = db.rawQuery(selectAll, null);
    		db.close();
    		while(cursol.moveToNext()){
    			Log.d("MessageList",cursol.getString(0) + " : " + cursol.getString(1) + " : " + cursol.getString(2) + " : " + cursol.getString(3));
    		}
    	}catch (Exception e) {
    		Log.d("insertList","ERROR!!SELECT FAILED");
    		return null;
		}
    	return cursol;
    }


}